import { AbstractSeeder } from '../abstract';
import { Prisma, PrismaClient } from '../../../src/generated/prisma';
import { DEPARTMENT_DATA } from './department.data';

export default class DepartmentSeed extends AbstractSeeder {
  name = 'Department' as const;
  data = DEPARTMENT_DATA;

  async exec(tx: Prisma.TransactionClient): Promise<void> {
    const root = await tx.department.upsert({
      where: { name: this.data.root.name },
      update: {},
      create: this.data.root,
    });

    await tx.department.createMany({
      data: this.data.level1.map(d => ({ ...d, parentDeptId: root.id })),
      skipDuplicates: true,
    });

    const parents = await tx.department.findMany({
      where: { name: { in: this.data.level2.map(d => d.parentName) } },
      select: { id: true, name: true },
    });
    const map = new Map(parents.map(p => [ p.name, p.id ]));
    await tx.department.createMany({
      data: this.data.level2.map(d => ({
        name: d.name,
        remark: d.remark,
        status: true,
        parentDeptId: map.get(d.parentName)!,
      })),
      skipDuplicates: true,
    });

    await tx.department.createMany({
      data: Array.from({ length: this.data.testCount }, (_, i) => ({
        name: `测试部门${ i }`,
        status: true,
      })),
      skipDuplicates: true,
    });
  }
}

if (require.main === module) {
  const prisma = new PrismaClient();
  new DepartmentSeed()
    .run(prisma)
    .catch(e => {
      console.error(e)
      process.exit(1)
    })
    .finally(() => prisma.$disconnect());
}

